const { axios } = require('../../utils/http')
const { socket } = require('../../utils/ws')
// const io = require('../../utils/socket')
Page({
  data: {
    callList: [],
    callValue: '',
    userInfo: {},
    task: null
  },
  onShow() {
    const userInfo = wx.getStorageSync('userInfo')
    this.setData({
      userInfo
    })
    this.getConnectSocket()
    this.listMessage()
    this.data.task.onOpen(res => {
      console.log('连接已经打开')
      this.sendMessage()
    })
    this.data.task.onClose(res => {
      console.log('连接关闭')
    })
    this.data.task.onMessage(res => {
      const sid = JSON.parse(res.data.slice(1))
    })
    // this.getLastCallList()
  },
  onLoad({ username }) {
    this.getCallList(username)
  },
  scrollBottom(isSend) {
    const query = wx.createSelectorQuery()
    query.selectViewport().scrollOffset()
    query.exec(function (res) {
      wx.pageScrollTo({
        scrollTop: res[0].scrollHeight,
        duration: isSend ? 300 : 0
      })
    })
  },
  getCallList(username) {
    axios
      .get('/chat/search', {
        params: {
          username,
          Tousername: '2628735401'
        }
      })
      .then(res => {
        this.setData({
          callList: res.data.data
        })
        wx.nextTick(() => {
          this.scrollBottom()
        })
      })
  },
  listMessage() {
    // socket.on('message', data => {
    //   console.log(data)
    // })
  },
  getConnectSocket(sid) {
    // const socket = io('http://99.248.208.30:3001')
    // const { username, realname } = this.data.userInfo
    // socket.emit('online', {
    //   username,
    //   realname,
    //   roomType: 'single'
    // })
    let url = 'wss://www.ttzxh.icu/api/socket/'
    const task = wx.connectSocket({
      url,
      header: {
        'content-type': 'application/json'
      },
      success: () => {
        console.log('success')
      },
      fail: res => {
        console.log(res)
      }
    })
    this.setData({
      task
    })
  },
  sendMessage() {
    const { task, callValue } = this.data
    task.send('message', {
      data: callValue,
      success: () => {
        this.setData({
          callValue: ''
        })
      }
    })
  }
})
